<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    :body-style="{ height: '450px' }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
import {computed, defineComponent, inject, ref, unref} from 'vue';
import {BasicForm, useForm} from '/@/components/Form';
import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
import {EpibolyUnitFormSchema} from "/src/views/ehs/epiboly/epiboly.data";
import {QcUnifyTransToChildProps} from "/#/QcUnify";
import {displayTitle} from "/@/utils/QcUnifyUtil";
import {OperationTypeEnum} from "/@/enums/appEnum";
import {addEpibolyUnit, updateEpibolyUnit} from "/@/api/ehs/epiboly";
import { useMessage } from '/@/hooks/web/useMessage';
import {EpibolyUnitDto} from "/@/api/ehs/model/epibolyModel";

export default defineComponent({
  name: 'AddOrUpdateEpibolyUnit',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],

  setup(_, { emit }) {
    const  {createMessage} = useMessage();
    console.log('AddOrUpdate.vue setup');
    const op = ref(OperationTypeEnum.UN_KNOWN);
    const unitId = ref('');
    const orgcode = ref('');

    // 注入模块名称
    const moduleName = inject<string>('moduleName') || '资质证照';
    // 标题--根据传入的模块名称+操作类型组合得到
    const modalTitle = ref('资质证照');

    const qcUnifyProps = ref<QcUnifyTransToChildProps>();
    /**
     * 显示的模块标题，用于显示在弹出框中的标题
     */
    let displayModuleTitle = computed(() => {
      return displayTitle(qcUnifyProps.value);
    });

    const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
      labelWidth: 120,
      schemas: EpibolyUnitFormSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    })

    /**
     * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
     */
    const [registerModal, { setModalProps, closeModal }]=useModalInner(async(data)=> {
      console.log('AddOrUpdate.vue useModalInner data',data);

      // 保存传入的参数
      if (data != undefined) {
        qcUnifyProps.value = unref(data);
      }


      //接收父组件传递的数据
      if (data?.operateType) {
        //判断是否传入操作类型属性
        op.value = data.operateType;
      }

      if (data?.id) {
        unitId.value = data.id;
      }

      if (data?.orgcode) {
        orgcode.value = data.orgcode;
      }
      // 设置模态框标题
      if (moduleName) {
        modalTitle.value = unref(moduleName);
      }
      if (op.value !== OperationTypeEnum.UN_KNOWN && op.value !== OperationTypeEnum.CUSTOME) {
        modalTitle.value += '--' + op.value;
      }
      resetFields(); // 重置表单，不等待
      setModalProps({ confirmLoading: false });


      // 始终设置组织代码（通过 updateSchema 确保字段存在）
      if (orgcode.value) {
        // 方式1：直接设置表单值
        setFieldsValue({ orgcode: orgcode.value });

        updateSchema({
          field: 'orgcode',
          defaultValue: orgcode.value
        });
      }


      // 如果是修改模式并且传入了数据，直接设置表单数据
      if (op.value === OperationTypeEnum.EDIT && data?.data) {
        // 直接使用传入的数据填充表单，确保包含所有必要字段
        const formData = {
          ...data.data,
          orgcode: orgcode.value, // 确保组织代码不丢失
          status: String(data.data.status || '1') // 确保状态是字符串
        };

         setFieldsValue(formData);
      }else{
        // 新增模式，设置默认值
        setFieldsValue({
          orgcode: orgcode.value,
          status: '1' // 默认状态
        });
      }
    })

    /**
     * 点击确认按钮，根据不同的op调用对应方法保存信息
     */
    async function onButtonOkClick() {
      try {
        const values=await validate()
        //这里可以添加表达那验证和提交逻辑
        setModalProps({ confirmLoading: true });

        //创建一个符合EpibolyUnitDto接口的数据对象
        const epiboluUnitData:EpibolyUnitDto={
          ...values,
          orgcode:orgcode.value
        }

          try {
            if (op.value === OperationTypeEnum.ADD ) {
              //调用接口进行保存
              const res = await addEpibolyUnit(epiboluUnitData);
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('保存成功。', 2);
              }
              opSuccess();
            } else if (op.value === OperationTypeEnum.EDIT) {
              //调用接口进行保存
              const updateData = {
                ...epiboluUnitData,
                unitid: unitId.value // 确保更新时包含ID
              };
              const res = await updateEpibolyUnit(updateData);
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            } else {
              createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
            }
          } finally {
            setModalProps({ confirmLoading: false });
          }
      }catch (error){
        console.error('表单验证失败:',error)
      }
    }

    //操作成功后
    function opSuccess() {
      closeModal();
      emit('success');
    }

    return {
      displayModuleTitle,
      registerForm,
      opSuccess,
      registerModal,
      onButtonOkClick,
    };
  },
});
</script>

<style scoped lang="less"></style>
